package com.koron.common.web.servlet;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Title: FileDownAction Description: 文件下载
 * 
 * @author DaiSn
 * @date 2019年3月13日
 */
@Controller
public class FileDownAction {

	@RequestMapping(value = "fileDown.htm")
	public void fileDown(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		int importType = Integer.parseInt(req.getParameter("importType"));
		String path = null;
		String name = null;
		switch (importType) {
		case 1:
			name = "水表模板.xls";
			path = req.getServletContext().getRealPath("/excelmodel/水表模板.xls");
			break;
		case 2:
			name = "集中器模板.xls";
			path = req.getServletContext().getRealPath("/excelmodel/集中器模板.xls");
			break;
		case 3:
			name = "采集器模板.xls";
			path = req.getServletContext().getRealPath("/excelmodel/采集器模板.xls");
			break;
		case 4:
			name = "RTU模板.xls";
			path = req.getServletContext().getRealPath("/excelmodel/RTU模板.xls");
			break;
		case 5:
			name = "通讯卡模板.xls";
			path = req.getServletContext().getRealPath("/excelmodel/通讯卡模板.xls");
			break;
		default:
			break;
		}
		// 第一步：设置响应类型
		resp.setContentType("application/force-download");// 应用程序强制下载
		// 第二读取文件
		File file = new File(path);
		// 获得输出流
		OutputStream out = resp.getOutputStream();
		// 通过输入流读取文件在输出
		FileInputStream inputStream = new FileInputStream(file);
		// 设置响应头，对文件进行url编码
		name = URLEncoder.encode(name, "UTF-8");
		resp.setHeader("Content-Disposition", "attachment;filename=" + name);
		resp.setContentLengthLong(file.length());

		// 第三步：老套路，开始copy
		byte[] b = new byte[1024 * 10];
		int len = 0;
		while ((len = inputStream.read(b)) != -1) {
			out.write(b, 0, len);
		}
		// out.flush();
		out.close();
		inputStream.close();
	}

}
